<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog v-model="props.addDialogVisible" :title="operateTitle" width="500" @close="handleVisible('cancel')">
    <el-form ref="formRef" size="small" :rules="rules" :model="form" label-width="110px">
      <el-form-item label="服务名称" prop="serverName">
        <el-input v-model="form.serverName" placeholder="请输入服务名称" :disabled="modelType === 'view'" />
      </el-form-item>
      <el-form-item label="模型： " prop="path">
        <el-cascader
          v-if="modelType !== 'edit'"
          ref="cascader"
          v-model="form.path"
          style="width: 100%"
          :options="modelTreeCopy"
          placeholder="请选择模型"
          :props="cascaderProps"
          @change="handleCascaderChange"
        />
        <el-input v-else v-model="form.modelName" :disabled="true" />
      </el-form-item>
      <el-form-item label="模型版本： " prop="modelVersion">
        <el-select v-model="form.modelVersion" placeholder="请选择模型版本" :disabled="modelType === 'edit'" @change="handleSelectChange">
          <el-option v-for="item in version" :key="item.versionNumber" :label="item.versionNumber" :value="item.versionNumber"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="要素库：" prop="parentId">
        <el-input v-model="form.databaseTypeName" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="业务场景：" prop="parentId">
        <el-input v-model="form.sceneName" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item v-if="form.systemName" label="业务系统：" prop="parentId">
        <el-input v-model="form.systemName" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="服务描述：" prop="description">
        <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" :disabled="modelType === 'view'" />
      </el-form-item>
      <el-form-item v-if="modelType !== 'add'" label="服务地址：" prop="serviceAddress">
        <el-input v-model="form.serviceAddress" type="textarea" :rows="3" placeholder="请输入描述" :disabled="true" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" @click="handleVisible('cancel')">取消</el-button>
        <el-button v-if="modelType !== 'view'" size="small" type="primary" @click="submitAdd">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getDataServicesList, createDataServices, updateDataServices } from '@/api/dataServices/index.ts';
import { getElementModel, getModellTree, getModelDetail } from '@/api/metaData/model.ts';
const props = defineProps(['addDialogVisible', 'operateType', 'serverType', 'rowData']);
const emits = defineEmits(['handleEvent']);
const modelType = ref('');
if (props.operateType) {
  modelType.value = props.operateType;
}
const cascader = ref();
const cascaderProps = ref({
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: true,
  disabled: (data: any) => {
    return isIdInTreeData(data.type);
  }
});
const modelTree = ref([]);
const modelTreeCopy = ref([]);
const version = ref([]);
const formRef = ref();
// 组织数据
const form = ref({
  id: props.rowData?.id || undefined,
  version: props.rowData?.version || {},
  serverName: props.rowData?.serverName || '',
  description: props.rowData?.description || '',
  databaseTypeId: props.rowData?.databaseTypeId || '',
  databaseTypeName: props.rowData?.databaseTypeName || '',
  sceneId: props.rowData?.sceneId || '',
  sceneName: props.rowData?.sceneName || '',
  systemId: props.rowData?.systemId || '',
  systemName: props.rowData?.systemName || '',
  modelName: props.rowData?.modelName || '',
  modelId: props.rowData?.modelId || undefined,
  modelVersion: props.rowData?.modelVersion || undefined,
  serverType: props.rowData?.serverType || props.serverType,
  serviceAddress: props.rowData?.serviceAddress || '',
  path: []
});
const rules = {
  serverName: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
  path: [{ required: true, message: '请选择模型', trigger: 'blur' }],
  modelVersion: [{ required: true, message: '请选择模型版本', trigger: 'blur' }]
};
const operateTitle = ref('');
watch(
  () => props.operateType,
  (newVal) => {
    if (newVal === 'add') {
      operateTitle.value = '添加服务地址';
    } else {
      operateTitle.value = '编辑服务地址';
    }
  },
  { immediate: true }
);
// 向父组件发出信号控制弹窗的隐藏
const handleVisible = (type) => {
  if (type === 'cancel') {
    emits('handleEvent', { type: 'view' });
  }
};

// 根据id，树结构查找父模型路径
const findParentModelPathById = (nodes, targetId, nodePath = []) => {
  // console.log('findParentModelPathById', nodes, targetId, nodePath);
  for (const node of nodes) {
    nodePath.push(node.id);
    if (node.id === targetId) {
      form.value.path = [...nodePath];
      break;
    }
    if (node.children && node.children.length > 0) {
      const foundPath = findParentModelPathById(node.children, targetId, nodePath);
      if (foundPath) {
        break;
      }
    }
    nodePath.pop();
  }
};
// 表单提交
const submitAdd = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      return;
    } else {
      // 发送请求
      if (props.operateType === 'edit') {
        updateDataServices(form.value).then((res) => {
          if (res?.code === 200) {
            ElMessage({ showClose: true, message: '修改成功', type: 'success' });
            emits('handleEvent', { type: 'view' });
          }
        });
      } else if (props.operateType === 'add') {
        createDataServices(form.value).then((res) => {
          if (res?.code === 200) {
            ElMessage({ showClose: true, message: '新增成功', type: 'success' });
            emits('handleEvent', { type: 'view' });
          }
        });
      }
    }
  });
};

// 获取级联选择器节点数据
const findNodeByIds = (nodes, ids) => {
  for (const node of nodes) {
    if (node.id === ids[ids.length - 1]) {
      return node;
    }
    if (node.children) {
      const foundNode = findNodeByIds(node.children, ids);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
};

// 绑定数据库
const handleCascaderChange = (valueArr) => {
  form.value.modelVersion = '';
  cascader.value.togglePopperVisible(false);
  const node = findNodeByIds(modelTreeCopy.value, valueArr);
  if (node) {
    const params = {
      nodeId: node.nodeId,
      modelId: node.id,
      pageQuery: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'id',
        isAsc: 'descending'
      },
      modelName: '',
      modelType: ''
    };
    getElementModel(params).then((res) => {
      if (res.code === 200) {
        version.value = res.rows;
      }
    });
  }
};
// 根据版本绑定要素库,业务场景,业务系统
const handleSelectChange = (value) => {
  const params = {
    id: ''
  };
  params.id = version.value.find((item) => item.versionNumber === value)?.id;
  getModelDetail(params).then((res) => {
    if (res.code === 200) {
      form.value.databaseTypeId = res.data.databaseTypeId;
      form.value.databaseTypeName = res.data.databaseTypeName;
      form.value.sceneId = res.data.sceneId;
      form.value.sceneName = res.data.sceneName;
      form.value.systemId = res.data.systemId;
      form.value.systemName = res.data.systemName;
      form.value.modelName = res.data.modelName;
      form.value.modelId = res.data.id;
    }
  });
};

// 处理树结构，筛选出模型树结构
function filterTreeWithModelLimit(nodes) {
  return nodes
    .map((node) => {
      if (node.type === 'model' || node.type === 'common_model') {
        node.children = null;
      } else {
        node.children = filterTreeWithModelLimit(node.children);
      }
      return node;
    })
    .filter((node) => node !== null);
}

// 递归处理不可选节点
const isIdInTreeData = (type) => {
  if (type === 'common_model' || type === 'model') {
    return false;
  }
  return true;
};

const getList = () => {
  const params = {
    pageSize: 9999,
    pageNum: 1
  };
  getDataServicesList(params).then((res) => {
    if (res.code === 200) {
    }
  });
  getModellTree(params).then((res) => {
    if (res.code === 200) {
      modelTree.value = filterTreeWithModelLimit([res.data]);
      modelTreeCopy.value = JSON.parse(JSON.stringify(modelTree.value));
      nextTick(() => {
        if (props.operateType === 'edit') {
          findParentModelPathById(modelTreeCopy.value, props.rowData?.modelId);
        }
        const node = findNodeByIds(modelTreeCopy.value, form.value.path);
        if (node) {
          const params = {
            nodeId: node.nodeId,
            modelId: props.rowData?.modelId,
            pageQuery: {
              pageNum: 1,
              pageSize: 10,
              orderByColumn: 'id',
              isAsc: 'descending'
            },
            modelName: '',
            modelType: ''
          };
          getElementModel(params).then((res) => {
            if (res.code === 200) {
              version.value = res.rows;
            }
          });
        }
      });
    }
  });
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.location-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px; /* 增加间隔 */
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.el-dialog__header {
  font-weight: bold;
}
</style>
